const { Sequelize } = require('sequelize');
const dbConfig = require('../config/database');

// 获取当前环境
const env = process.env.NODE_ENV || 'development';
const config = dbConfig[env];

// 创建Sequelize实例
const sequelize = new Sequelize(
  config.database,
  config.username,
  config.password,
  {
    host: config.host,
    port: config.port,
    dialect: config.dialect,
    logging: config.logging,
    pool: config.pool
  }
);

// 导入模型
const db = {
  sequelize,
  Sequelize,
  User: require('./user')(sequelize, Sequelize),
  SudokuPuzzle: require('./game')(sequelize, Sequelize),
  SudokuAnswer: require('./answers')(sequelize, Sequelize),
  SudokuAction: require('./action')(sequelize, Sequelize)
};

// 设置模型关联
// 题库与解答的关联
db.SudokuPuzzle.hasMany(db.SudokuAnswer, { 
  foreignKey: 'puzzleId', 
  as: 'answers' 
});
db.SudokuAnswer.belongsTo(db.SudokuPuzzle, { 
  foreignKey: 'puzzleId', 
  as: 'puzzle' 
});

// 题库与操作的关联
db.SudokuPuzzle.hasMany(db.SudokuAction, { 
  foreignKey: 'puzzleId', 
  as: 'actions' 
});
db.SudokuAction.belongsTo(db.SudokuPuzzle, { 
  foreignKey: 'puzzleId', 
  as: 'puzzle' 
});

// 用户与解答的关联 (如果有用户系统)
if (db.User) {
  db.User.hasMany(db.SudokuAnswer, { 
    foreignKey: 'userId', 
    as: 'answers' 
  });
  db.SudokuAnswer.belongsTo(db.User, { 
    foreignKey: 'userId', 
    as: 'user' 
  });

  // 用户与操作的关联
  db.User.hasMany(db.SudokuAction, { 
    foreignKey: 'userId', 
    as: 'actions' 
  });
  db.SudokuAction.belongsTo(db.User, { 
    foreignKey: 'userId', 
    as: 'user' 
  });
}

module.exports = db;
